END {Log("ERROR: $@") if $@}
use strict;
use LWP::UserAgent;
use HTTP::Request;
use Net::SMTP;
use File::Spec;
#use Win32::Daemon;
use Win32::Daemon::Simple
	Service => 'WWCOMSiteChecker',
	Name => 'WWCOMSiteChecker',
	Version => '0.1',
	Info => {
		display =>  'WWCOM Site Checker',
		description => 'Site Checker Service for Wigan-Warriors.com',
		user    =>  '',
		pwd     =>  '',
		interactive => 0,
	},
	Params => {
		Tick => 0,
		Talkative => 0,
		Interval => 60,
		LogFile => "C:/Wwcom/v2.0/scripts/TestSimple.log",
		Description => <<'*END*',
Tick : (0/1) controls whether the service writes a "tick" message to
  the log once a minute if there's nothing to do
Talkative : (0/1) controls the amount of logging information
Interval : how often does the service look for new or modified files
  (in minutes)
*END*
	},
	param_modify => {
		LogFile => sub {File::Spec->rel2abs($_[0])},
		tAlkative => sub {undef},
	};

my $ROOTDIR= 'c:/wwcom/v2.0';

ServiceLoop(\&doSomething);
Log("Going down");
exit;

sub doSomething {
	for my $url ("http://www.wiganwarriors.com/index.asp",
			"http://www.wigantoday.net/newsfront.aspx?sectionid=68",
			"http://www.wiganwarriors.com/MidContent.asp?cid=86",
			"http://www.wiganwarriors.com/Fixtures.asp?catid=8",
			"http://www.superleague.co.uk/news",
			"http://rfl.uk.com/Templates/RFLDefault.asp?modeID=Content&uID=95") {
		Log("Checking $url");
		$url=~ /\/([^\/]+?)$/;
		my $fname= $1;
		$fname=~ s/\?//g;  #remove invalid filename characters
		if ($fname eq '') {
			$fname= $url;
			$fname=~ s/[\/\.\:]//g;
			print "$url $fname";
		}
		
		my ($f1,$f2)= getURL($url,$fname);
		if (defined ($f1) and defined ($f2)) {
			my $diff= diffFiles($f1,$f2);
			Log("Difference: $diff");
			if ($diff) {
				sendemail('Mike Rogers','mike.rogers@manchester.ac.uk',
					qq~Subject: WWCOM Found difference!\n\n
					$url\n\n~);
			}
			Log("Done");
		} else {
			Log ("Failed");
		}
	}
}

sub getURL {
	my $furl= shift;
	my $fname= shift;
		
	my $fname1= "$ROOTDIR/data/incoming/sitecheck/$fname";
	my $fname2= $fname1.'.old';    
	rename $fname1,$fname2 if (-e $fname1);  #moves fname1 to fname2 - deletes fname1
	
		my $agent= new LWP::UserAgent;
	$agent->agent("Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.0.1) Gecko/20020823 Netscape/7.0" . $agent->agent);
	#$agent->agent("Wigan-Warriors.com/2.0 " . $agent->agent);
	#$agent->proxy(['http', 'ftp'], 'http://wwwcache.mcc.ac.uk:3128/');
	$agent->timeout(30);  #30 second timeout
	my $request= HTTP::Request->new(GET => "$furl");
	$request->header(Accept => "text/html, text/plain, image/*");
	
	my $res= $agent->request($request,$fname1);
	if (!$res->is_success) {
		Log $res->as_string;
		return (undef,undef);
	}
	
	return ($fname1,$fname2);
}


sub diffFiles {
	my $fname1= shift;
	my $fname2= shift;

	open(F,"<$fname1");
	my @f1= <F>;
	close(F);

	open(F,"<$fname2");
	my @f2= <F>;
	close(F);    
	
	my $f1= join('',@f1);
	my $f2= join('',@f2);
	
	#remove crap and ads
	$f1=~ s/\<\!\-\- Content left col \-\-\>.*\<\!\-\- end left col \-\-\>//seg;
	$f2=~ s/\<\!\-\- Content left col \-\-\>.*\<\!\-\- end left col \-\-\>//seg;
	$f1=~ s/\<\!\-\- begin rightcolumn \-\-\>.*\<\!\-\- end right column \-\-\>//seg;
	$f2=~ s/\<\!\-\- begin rightcolumn \-\-\>.*\<\!\-\- end right column \-\-\>//seg;
	#wep
	$f1=~ s/^.*\<div id\=\"newsfront\"\>//seg;
	$f2=~ s/^.*\<div id\=\"newsfront\"\>//seg;
	$f1=~ s/\<h1\>Search Our News Archive\<\/h1\>.*$//seg;
	$f2=~ s/\<h1\>Search Our News Archive\<\/h1\>.*$//seg;
	
	
	$f1=~ s/<.*?>//seg;  #remove html tags
	$f2=~ s/<.*?>//seg;  #remove html tags
	
	return ($f1 ne $f2);
}


sub sendemail {
	my $to= shift;
	my $email= shift;
	my $message= shift;
		
	my $from= "webmaster\@wigan-warriors.com";
	  
	my $mail_message = <<__END_OF_MAIL__;
To: $to <$email>
From: $from
$message
  
__END_OF_MAIL__
  
	 my $smtp_server = 'mailrouter.mcc.ac.uk';
  
	  # init the server
	my $smtp = Net::SMTP->new(
							$smtp_server,
							Timeout => 60, 
							Debug   => 0,
						   );

	if (defined $smtp) {  
		$smtp->mail($from) or Log("Failed to initialise []\n");
		
		$smtp->to(qq~$email~) or Log("Failed to specify a recipient [$to <$email>]\n");
		Log ("Sent mail to: $to <$email>");
		$smtp->data([$mail_message])  or Log("Failed to send a message\n");
	
		$smtp->quit or Log("Failed to quit\n");
	} else {
		Log "Failed";
	}
	return;
		  
  } #  end of sub send_mail


__END__

# not so simple
sub doSomething {
	Log("Doing something");
	foreach (1..5) {
		Log " task $_";
		sleep(5 + rand(5)); # process the task
		Log "  done $_";
		DoEvents(
			sub {LogNT "Thanks, I'll take a nap."}, # pause
			sub {LogNT "OK, back to work."}, # unpause
			sub {LogNT "Mama they killed me!"; return 1} # stop
		);
	}
	Log("Done something");
}

# ever worse
sub doSomething {
	Log("Doing something");
	sleep(1 + rand(5)); # prepare for the tasks
	LogNT " on to the tasks...";
	foreach (1..5) {
		Log "  task $_";
		sleep(5 + rand(5)); # process the task
		Log "   done $_";

		last if (SERVICE_STOP_PENDING == DoEvents(
			sub {Log "Thanks, I'll take a nap."}, # pause
			sub {Log "OK, back to work."}, # unpause
			sub {Log "Mama they wanna kill me!"; return 0} # stop
		));
	}
	LogNT " done all tasks";
	sleep(1 + rand(5)); # cleanup after the tasks
	Log("Done something");
}

